//分页器数据
let pageInfo = {
  //当前页码
  page: 1,
  //一页几条
  pageSize: 10,
  //总条数
  total: 23,
  //商品名称
  productName: '',
  //是否付款
  isPayment: 1,
  //供应商id
  providerId: '',
  //当前页的账单列表
  billList: [],
  getTotal() {
    let total = this.total
    let totalPage = this.pageSize
    return Math.ceil(total / totalPage)
  },
  //计算后的总页数
  totalPage: 0,
}

let baseUrl = `http://146.56.230.35:3007/`

$(function () {
  initProviderList()
})

/**
 * 1、页面已加载就请求所有的供应商并渲染到页面中
 * @date 2021-03-26
 * @returns {any}
 */
async function initProviderList() {
  //1、请求所有供应商列表，在页面进行加载
  let res = await getProviderList()
  console.log(res)
  //2、判断请求结果是否成功
  if (res.code !== 200) {
    return alert(res.msg)
  }
  //3、获得供应商列表
  let providerList = res.data.list
  //4、执行渲染操作
  renderProviderList(providerList)
}

/**
 * 2、执行供应商列表的渲染操作
 * @date 2021-03-26
 * @param {any} arr
 * @returns {any}
 */
function renderProviderList(arr) {
  if (!arr || arr.length === 0) {
    return
  }
  let tigong = $('.tigong')
  tigong.empty()
  tigong.append(`<option value="0">--请选择--</option>`)
  arr.forEach((item) => {
    let op = `<option value="${item.id}">${item.proName}</option>`
    tigong.append(op)
  })
}

/**
 * 3、供应商列表的请求
 * @date 2021-03-26
 * @returns {any}
 */
function getProviderList() {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: baseUrl + 'provider/getProviderList',
      type: 'GET',
      success(res) {
        resolve(res)
      },
      error(err) {
        reject(err)
      },
      headers: {
        token: getToken().token,
      },
    })
  })
}

/**
 * 请求账单的分页列表
 * @date 2021-03-27
 * @returns {any}
 */
function getBillList() {
  let params = {
    page: pageInfo.page,
    pageSize: pageInfo.pageSize,
  }
  let productName = $('productName').val()
  if (productName) {
    params.productName = productName
    pageInfo.productName = productName
  }
  let providerId = +$('.tigong').val()
  if (providerId !== 0) {
    params.providerId = providerId
    pageInfo.providerId = providerId
  }
  let isPayment = +$('.isPayment').val()
  if (isPayment !== 0) {
    params.isPayment = isPayment
    pageInfo.isPayment = isPayment
  }
  return new Promise((resolve, reject) => {
    $.ajax({
      url: baseUrl + 'bill/getBillList',
      type: 'GET',
      data: params,
      success(res) {
        resolve(res)
      },
      error(err) {
        reject(err)
      },
      headers: { token: getToken().token },
    })
  })
}

async function renderBillList() {
  let res = null
  try {
    //获得返回数据
    res = await getBillList()
  } catch (error) {
    console.log(error)
  }
  if (!res) {
    return console.log('请求数据失败')
  }
  if (res.code !== 200) {
    return console.log(res.msg)
  }
  //进行数据解析
  let list = res.data.list
  let count = res.data.count
  pageInfo.total = count
  pageInfo.billList = list
  //数据渲染
  let table = $('.providerTable')
  table.find('tr:not(:first)').remove()
  for (let i = 0; i < list.length; i++) {
    let tr = `
      <tr>
        <td>${list[i].billCode}</td>
        <td>${list[i].productName}</td>
        <td>${list[i].proName}</td>
        <td>&yen;${list[i].totalPrice}</td>
        <td>${list[i].isPayment === 1 ? '已付款' : '未付款'}</td>
        <td>${list[i].createdAt}</td>
        <td>
          <a href="billView.html?id=${
            list[i].id
          }"><img src="img/read.png" alt="查看" title="查看"/></a>
          <a href="billUpdate.htmlid=${
            list[i].id
          }"><img src="img/xiugai.png" alt="修改" title="修改"/></a>
          <a href="##" class="removeBill" data-id="${
            list[i].id
          }"><img src="img/schu.png" alt="删除" title="删除"/></a>
        </td>
      </tr>
    `
    table.append(tr)
  }
  //给删除按钮绑定事件
  $('.removeBill').click(function () {
    let flag = confirm('确定要删除吗？')
    console.log('flag=' + flag)
  })
}

async function initPager(page) {
  pageInfo.pageSize = +$('.opt').val()
  await renderBillList()
  //拼接前先清空所有分页器
  let pageItem = $('.page-item')
  if (pageItem) {
    pageItem.remove()
  }
  //设置分页器的起点和终点
  let start = page <= 6 ? 1 : page - 5
  let end = start + 9
  //对总页数的计算
  pageInfo.totalPage = pageInfo.getTotal()
  if (end >= pageInfo.totalPage) {
    end = pageInfo.totalPage
  }
  //拼接分页器页码
  for (let i = start; i <= end; i++) {
    let a = $(`<a href="##" class="page-item">${i}</a>`)
    if (i === page) {
      a = $(`<a href="##" class="page-item active">${i}</a>`)
    }
    a.insertBefore($('.next-page'))
  }
  //把当前页码写入到指定的位置
  $('.desc span:eq(0)').html(pageInfo.totalPage)
  $('.desc span:eq(1)').html(page)
  $('.pager').val(page)
  //保证每次重新拼接分页器都有点击效果
  $('.page-item').click(function () {
    let pageNum = +$(this).html()
    pageInfo.page = pageNum
    initPager(pageInfo.page)
  })
}

$(function () {
  initPager(pageInfo.page)
})
